package cn.autoOffice.interceptors;

import cn.autoOffice.common.utils.HttpUtils;
import cn.autoOffice.common.utils.ResultCodeEnum;
import cn.autoOffice.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// @Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

    @Autowired
    private RedisService redisService;

    public static String[] EXCLUDE_URI = new String[]{"/user/login","/user/register","/selectEmpInfo"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是注册或者登录请求
        logger.info("====进入拦截器");
        String servletPath = request.getServletPath();
        for(String url : EXCLUDE_URI){
            if(url.equals(servletPath)){
                logger.info("#################此接口：" + servletPath + "直接放行#################");
                return true;
            }
        }

        String token = request.getHeader("token");
        logger.info("#################从header中得到token[" + token + "]#################");
        if (!StringUtils.hasLength(token)) {
            HttpUtils.outputJson(response, ResultCodeEnum.PARAM_AUTH_TOKEN_EMPTY);
            return false;
        }

        String userID = redisService.getValue(token);
        if(userID!=null){
            return true;
        }else{
            HttpUtils.outputJson(response, ResultCodeEnum.PARAM_AUTH_NOT_LOGIN);
            return false;
        }
    }

}
